// utils/storage.ts
const KEY_USER: string = "KEY_USER";

// utils/storage.ts
export interface UserInfo {
  id: string; // 改为小写
  phone: string; // 改为小写
  state: number; // 改为小写
  name: string; // 改为小写
}

// 类型守卫也相应修改
export function isUserInfo(data: any): data is UserInfo {
  return (
    data &&
    typeof data.id === "string" &&
    typeof data.phone === "string" &&
    typeof data.state === "number" &&
    typeof data.name === "string"
  );
}

export default {
  setUser(user: UserInfo) {
    sessionStorage.setItem(KEY_USER, JSON.stringify(user));
  },
  removeUser() {
    sessionStorage.removeItem(KEY_USER);
  },
  getUser(): UserInfo | null {
    try {
      const userStr = sessionStorage.getItem(KEY_USER);
      if (!userStr) return null;

      const parsed = JSON.parse(userStr);
      return isUserInfo(parsed) ? parsed : null;
    } catch (error) {
      console.error("Failed to parse user data:", error);
      this.removeUser(); // 清除无效数据
      return null;
    }
  },
};
